import { ElMessage } from 'element-plus'
// import qs from 'qs'
import { SUCCESS_CODE } from '../../constants'

import { useUserStoreWithOut } from '@/store/modules/user'

// 请求拦截器
const defaultRequestInterceptors = (config: any) => {
  const { getTokenKey, getAccessToken } = useUserStoreWithOut()
  const { method, data, } = config
  if (method === 'post') {
    const isMock = import.meta.env.VITE_APP_MOCK
    if (isMock === "true") {
      config.data.headers = {
        tokenKey: getTokenKey,
        token: getAccessToken
      }
    }
    config.data = JSON.stringify(data)
  }
  if (method === 'get') {
    const isMock = import.meta.env.VITE_USE_MOCK
    if (isMock === "true") {
      config.data = {
        ...config.data, headers: {
          tokenKey: getTokenKey,
          token: getAccessToken
        },
      }
    }
  }
  return config
}

// 响应拦截器
const defaultResponseInterceptors = (response: any) => {
  if (response?.config?.responseType === 'blob') {
    // 如果是文件流，直接过
    return response
  } else if (response.data.code === SUCCESS_CODE) {
    return response
  } else {
    if (response?.data?.code === 401) {
      ElMessage.error(response?.data?.msg || '登录失效')
      // const userStore = useUserStoreWithOut()
      // userStore.logout()
      return Promise.reject(response)
    } else {
      // 错误响应在这里统一处理
      // 错误提示
      // ElMessage.error(response?.data?.msg)
      // return Promise.reject(response.data)
      return response
    }
  }
}

export {
  defaultRequestInterceptors,
  defaultResponseInterceptors
}